<template>
  <div class="about-us-container">
    <el-card shadow="never" class="form-card">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="demo-form">
        <el-form-item label="页面标题" prop="title">
          <el-input disabled="true" v-model="form.title" placeholder="请输入页面标题" />
        </el-form-item>

        <el-form-item label="富文本" prop="content">
          <el-skeleton :loading="loading" animated>
            <rich-txt 
              :modelValue="form.content" 
              @update:modelValue="(val) => { form.content = val }"
            />
          </el-skeleton>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import api from "@/request/api.js";
import richTxt from "@/components/richTxt.vue";

export default {
  name: "AboutUs",
  components: { richTxt },
  data() {
    return {
      loading: false,
      form: {
        title: "",
        content: ""
      },
      rules: {
        title: [{ required: true, message: "请输入页面标题", trigger: "blur" }],
        content: [{ required: true, message: "请输入内容", trigger: "blur" }]
      }
    };
  },
  created() {
    this.loadData();
  },
  methods: {
    async loadData() {
      this.loading = true;
      try {
        const res = await api.aboutUs.getDetail({ system_id:2  });
        // 更安全的数据结构访问方式
        const data = res.data?.content?.data || res.data || {};
        this.form = {
          title: data.system_key || this.form.title,
          content: data.system_value || this.form.content
        };
      } catch (error) {
        console.error("加载数据失败:", error);
        this.$message.error("加载数据失败");
      } finally {
        this.loading = false;
      }
    },
    submitForm() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return false;
        
        try {
          const res = await api.aboutUs.update({ 
            system_id: 2, 
            system_value: this.form.content
          });
          
          if (res.data.code === 200) {
            this.$message.success("保存成功");
            await this.loadData();
          }
        } catch (error) {
          console.error("保存失败:", error);
          this.$message.error("保存失败");
        }
      });
    },
    handleReset() {
      this.$refs.formRef.resetFields();
      // 对于可能没有正确重置的富文本，手动重置
      this.loadData();
    }
  }
};
</script>

<style scoped>
.about-us-container {
  padding: 20px;
}

.form-card {
  margin-bottom: 20px;
}
</style>